const path = require('path');

const webpack = require('webpack');
const HappyPack = require('happypack');
const WebpackBar = require('webpackbar');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

const { PUBLIC_PATH, PRODUCTION, DEFINE_PLUGIN_ENV } = require('./variables');

function getPlugins() {
  const htmlWebpackPlugin = new HtmlWebpackPlugin({
    template: path.join(PUBLIC_PATH, 'index.html'),
    filename: 'index.html',
    favicon: path.join(PUBLIC_PATH, 'favicon.ico'),
    inject: true, // true:插入body底部，head:插入head标签，false:不生成js文件
    title: '',
    minify: {
      removeComments: true, // 删除注释
      collapseWhitespace: true,
      minifyCSS: true, // 压缩 HTML 中的 css 代码
      minifyJS: true, // 压缩 HTML 中的 js 代码
    },
  });
  const miniCssPlugin = new MiniCssExtractPlugin({
    filename: PRODUCTION ? 'assets/css/[name].[contenthash:8].css' : 'assets/css/[name].css',
    chunkFilename: PRODUCTION
      ? 'assets/css/[name].[contenthash:8].chunk.css'
      : 'assets/css/[name].chunk.css',
    // 常遇到如下警告，Conflicting order. Following module has been added:…。
    // 此警告意思为在不同的js中引用相同的css时，先后顺序不一致。也就是说，在1.js中先后引入a.css和b.css，而在2.js中引入的却是b.css和a.css，此时会有这个warning
    ignoreOrder: true,
  });
  const happyPack = new HappyPack({
    id: 'babel',
    loaders: ['babel-loader?cacheDirectory'],
    threads: require('os').cpus().length,
  });
  const definePlugin = new webpack.DefinePlugin({
    'process.env': DEFINE_PLUGIN_ENV,
  });

  return [htmlWebpackPlugin, miniCssPlugin, happyPack, definePlugin, new WebpackBar()];
}

module.exports = {
  getPlugins,
};
